<?php
/**
 * FastApp.
 * 9/13/24
 * @Author deepsea159
 * @Contact telegram:deepsea159
 */

namespace App\Fastapp;

use Hyperf\HttpMessage\Upload\UploadedFile;
use Mine\Event\UploadAfter;
use Mine\Exception\NormalStatusException;
use Mine\Helper\Str;

class FastappAdminUpload extends \Mine\MineUpload
{

    protected function handleUpload(UploadedFile $uploadedFile, array $config): array
    {
        $tmpFile = $uploadedFile->getPath() . '/' . $uploadedFile->getFilename();
        $path = $this->getPath($config['path'] ?? null, $this->getStorageMode() != 1);
        $filename = $this->getNewName() . '.' . Str::lower($uploadedFile->getExtension());

        try {
            $file_path = $path . '/' . $filename;
            if (!$this->filesystem->directoryExists(dirname($file_path))) $this->filesystem->createDirectory(dirname($file_path), ['visibility' => 'public']);
            $this->filesystem->writeStream($file_path, $uploadedFile->getStream()->detach());
        } catch (\Exception $e) {
            throw new NormalStatusException($e->getMessage(), 500);
        }
        $fileInfo = [
            'storage_mode' => $this->getStorageMode(),
            'origin_name' => $uploadedFile->getClientFilename(),
            'object_name' => $filename,
            'mime_type' => $uploadedFile->getClientMediaType(),
            'storage_path' => $path,
            'hash' => md5_file($tmpFile),
            'suffix' => Str::lower($uploadedFile->getExtension()),
            'size_byte' => $uploadedFile->getSize(),
            'size_info' => format_size($uploadedFile->getSize()),
            'url' => $this->assembleUrl($config['path'] ?? null, $filename),
        ];

        $this->evDispatcher->dispatch(new UploadAfter($fileInfo));

        return $fileInfo;
    }

}